﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using OBUCare.Core.Models;
using OBUCare.Core.DataAccess;
using Telerik.Web.Mvc;
using OBUCare.Web.Models;
using OBUCare.Web.Infrastructure;
using OBUCare.Core.BL;
using OBUCare.Core.Common;

namespace OBUCare.Web.Controllers
{
    /// <summary>
    /// 费用相关Controller
    /// </summary>
    public class CostController : Controller
    {
        private OBU_CAREContext db = new OBU_CAREContext();
        OBUCareOrderMgr obuMgr = new OBUCareOrderMgr();
        UserMgr uMgr = new UserMgr();
        ConfigMgr configMgr = new ConfigMgr();
        static string id = "";

        public ActionResult Index()
        {
             id = "";
            if (Request["id"] != null)
                id = Request["id"].ToString();
            return View();
        }

        [GridAction]
        public ActionResult List()
        {
            string  sqlWhere = "";
            if (id != "")
            {
                sqlWhere = " ID IN (";
                var  idList= id.Split(',').ConvertTo(s => s.ToString());
                idList.Each(i =>
                    {
                        sqlWhere += i.ToString() + ",";
                    });
                sqlWhere = sqlWhere.Substring(0, sqlWhere.Length - 1) + ")";
            }
            var result = obuMgr.GetRepairOrders(sqlWhere);

            List<CostModel> list = new System.Collections.Generic.List<CostModel>();

            if (result.Count() > 0)
            {
                result.Each(r =>
                    {

                        var repairFeeList = obuMgr.getRepairFee(r.ID).Sum(f=>f.PRICE);
                      

                        var repairFeeAdjust = obuMgr.getRepairFeeAdjust(r.ID, AdjustType.AdjustRepairFee).ToList().Sum(f=>f.AMOUNT);//维修费调整信息

                        
                        var serviceFeeAdjust = obuMgr.getRepairFeeAdjust(r.ID, AdjustType.AdjustServiceFee).ToList().Sum(f=>f.AMOUNT);//服务费调整

                        REPAIR_ORDER_TRACKING o = (from i in new OBU_CAREContext().REPAIR_ORDER_TRACKING.ToList()
                                                   where i.REPAIR_ORDER_ID == r.ID &&
                                                   i.REPAIR_ORDER_Status == Convert.ToInt32(RepairOrderStatus.InformedCustomer)
                                                   select i)
                                                 .FirstOrDefault();
                      int  infocustomerDate = o == null || o.CREATED_DATE == null ? 0 :
                            (DateTime.Now -o.CREATED_DATE.AddDays(Convert.ToInt32(ServiceFeeCheck.ServiceFeeDay))).Days < 0 ? 0 :
                            (DateTime.Now -o.CREATED_DATE.AddDays(Convert.ToInt32(ServiceFeeCheck.ServiceFeeDay))).Days;

                      var serviceFee  =r.SPARE_OBU_ISSUE_DATE==null&&r.SPARE_OBU_NO==null && r.SPARE_OBU_PRICE==null?0
                          : Convert.ToInt32(infocustomerDate * ServiceFeeCheck.ServiceFeePrice.ToInt());//如果没有备签就不算服务费

                        var cm = new CostModel() {Id=r.ID,RepairOrders=r,RepairFeeTotal=(repairFeeList+repairFeeAdjust).ToString(),ServiceFeeTotal=(serviceFee+serviceFeeAdjust).ToString() };
                        list.Add(cm);
                    });
            }

         


            var temp = new GridModel(list);
            return View(temp);
        }

        private IEnumerable<RepairOrderViewModel> GetRepairOrders()
        {
            var items = db.REPAIR_ORDERS.ToList();
            var results = from item in items
                          select item;

            var list = (from c in results
                        select new RepairOrderViewModel(c)).ToList();


            return list;
        }

        /// <summary>
        /// 调整费用
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ConfirmAdjust(string strIDs, string RepairFeeAdjustAmount, string RepairFeeAdjustRemark, string ServiceFeeAdjustAmount, string ServiceFeeAdjustRemark)
        {
            bool success = false;
            string message = null;

            try
            {
                var u = UIUtility.GetCurrentUser();
                List<REPAIR_ORDER_ADJUST> list = new List<REPAIR_ORDER_ADJUST>();
                var idArray = strIDs.Split(',');

                idArray.Each(id =>
                    {
                        list.CustomizeAddRange(toREPAIR_ORDER_ADJUST(id, RepairFeeAdjustAmount, RepairFeeAdjustRemark, ServiceFeeAdjustAmount, ServiceFeeAdjustRemark, u));
                    });

                success = obuMgr.AdjustRepariOrderFee(list);
            }
            catch (Exception ex)
            {
                success = false;
                message = ex.Message;
                TraceHelper.TraceError("调整费用失败：",ex);
            }

            return Json(new { success = success, message = message });
        }

        private List<REPAIR_ORDER_ADJUST> toREPAIR_ORDER_ADJUST(string id, string RepairFeeAdjustAmount, string RepairFeeAdjustRemark, string ServiceFeeAdjustAmount, string ServiceFeeAdjustRemark, OPERATOR u)
        {
            List<REPAIR_ORDER_ADJUST> list = new List<REPAIR_ORDER_ADJUST>();
            decimal? amount = RepairFeeAdjustAmount.Todecimal();
            long repairOrderID = id.ToLong().Value;
            //维修费
            if (amount.HasValue && amount.Value != 0)
            {
                REPAIR_ORDER_ADJUST m = new REPAIR_ORDER_ADJUST();
                m.REPAIR_ORDER_ID = repairOrderID;

                m.ADJUST_TYPE = AdjustType.AdjustRepairFee.ToInt().Value;
                m.AMOUNT = amount.Value;
                m.COMMENT = RepairFeeAdjustRemark;
                m.CREATED_BY = u.OPERATOR_NO;
                m.CREATED_DATE = DateTime.Now;
                m.MODIFY_BY = u.OPERATOR_NO;
                m.MODIFY_DATE = DateTime.Now;
                list.Add(m);
            }

            //服务费
            amount = ServiceFeeAdjustAmount.Todecimal();
            if (amount.HasValue && amount.Value != 0)
            {
                REPAIR_ORDER_ADJUST m = new REPAIR_ORDER_ADJUST();
                m.REPAIR_ORDER_ID = repairOrderID;

                m.ADJUST_TYPE = AdjustType.AdjustServiceFee.ToInt().Value;
                m.AMOUNT = amount.Value;
                m.COMMENT = ServiceFeeAdjustRemark;
                m.CREATED_BY = u.OPERATOR_NO;
                m.CREATED_DATE = DateTime.Now;
                m.MODIFY_BY = u.OPERATOR_NO;
                m.MODIFY_DATE = DateTime.Now;
                list.Add(m);
            }

            return list;
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            obuMgr.Dispose();
            configMgr.Dispose();
            uMgr.Dispose();
            base.Dispose(disposing);
        }
    }
}
